package cn.com.libertymutual.core.web;

import cn.com.libertymutual.core.exception.CustomLangException;
import cn.com.libertymutual.core.util.BeanUtilExt;

/**
 * @author bob.kuang
 *
 */
public class ServiceResult {
	/**
	 * 成功
	 */
	public static final int STATE_SUCCESS = 0;
	/**
	 * 应用异常
	 */
	public static final int STATE_APP_EXCEPTION = 1;
	/**
	 * 其他异常
	 */
	public static final int STATE_EXCEPTION = 2;
	/**
	 * 没有登录
	 */
	public static final int STATE_NO_SESSION = 3;

	// public static ServiceResult noSession = new ServiceResult(null,
	// STATE_NO_SESSION);

	private Object result;

	private int state;

	private String resCode;

	private String token;

	public ServiceResult() {
	}

	public ServiceResult(Object result, int state) {
		this.result = result;
		this.state = state;
	}

	public ServiceResult(int state) {
		this.result = "未知错误";
		this.state = state;
	}

	public Object getResult() {
		return result == null ? "" : result;
	}

	public void setResult(Object result) {
		this.result = result;
	}

	public <L> L getEntity(Class<L> responseType) {
		return BeanUtilExt.copy(responseType, result);
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String getResCode() {
		return resCode;
	}

	public void setResCode(String resCode) {
		this.resCode = resCode;
	}

	public void setSuccess() {
		this.state = STATE_SUCCESS;
	}

	public void setFail() {
		this.state = STATE_EXCEPTION;
	}

	public void setAppFail() {
		this.state = STATE_APP_EXCEPTION;
	}

	public void setAppFail(String message) {
		this.state = STATE_APP_EXCEPTION;
		this.result = message;
	}

	public void setAppFail(CustomLangException ee) {
		this.state = STATE_APP_EXCEPTION;
		this.resCode = String.valueOf(ee.getErrorCode());
		this.result = this.result == null ? ee.getErrorMessage() : this.result;
	}

	public String getToken() {
		return this.token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public boolean isSuccess() {
		return this.state == STATE_SUCCESS;
	}

	@Override
	public String toString() {
		return "ServiceResult [result=" + result + ", state=" + state + ", resCode=" + resCode + ", token=" + token + "]";
	}

}